<template>
  <el-autocomplete v-model="category" :fetch-suggestions="querySearch" :placeholder="placeholder" clearable @input="change" />
</template>

<script>
import { mapGetters } from 'vuex'
import { createOrupdateDictionary } from '@/api/sys/dictionary'

export default {
  name: 'DictGroupInput',
  props: {
    /**
     * 输入框值
     * 父组件中使用 :value.sync="value"
     */
    value: {
      type: String,
      default: ''
    },
    /**
     * 字典组
     */
    dictGroup: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      category: ''
    }
  },
  computed: {
    ...mapGetters(['uid', 'dictionaries']),
    categories() {
      return this.dictionaries.filter(category => category.dictGroup === this.dictGroup)
    }
  },
  created() {
    console.log('CategoryInput')
    this.category = this.value
    this.$on('newDict', function(value) {
      this.newDict(value)
    })
  },
  methods: {
    querySearch(str, cb) {
      const results = str ? this.categories.filter(this.createFilter(str)) : this.categories
      cb(results)
    },
    createFilter(queryString) {
      return category => {
        return category.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    change(value) {
      this.$emit('update:value', value)
    },
    reset(value) {
      this.category = value
      this.$emit('update:value', value)
    },
    newDict(value) {
      if (value) {
        const dict = this.categories.find(v => v.value === value)
        if (!dict) {
          const form = {
            uid: this.uid,
            text: value,
            code: value,
            textColor: '#000000',
            dictGroup: this.dictGroup,
            description: 'Autocomplete'
          }
          this.submitForm(form)
        }
      }
    },
    submitForm(form) {
      createOrupdateDictionary(form).then(response => {
        this.$store.dispatch('dictionary/setDictionaries', this.uid)
      })
    }
  }
}
</script>
